package biz.yfsoft.app.fastframework.interceptor;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import biz.yfsoft.app.fastframework.bo.Bo;
import biz.yfsoft.app.fastframework.core.BaseFastController;
import biz.yfsoft.app.fastframework.core.Fast;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * 管理员的拦截器
 * @author YFsoft
 *
 */
public class AdminIntercept implements Interceptor{

	@Override
	public void intercept(ActionInvocation ai) {
		Controller ctr = ai.getController();
		if(! (ctr instanceof BaseFastController)){
			ai.invoke();
			return;
		}
		BaseFastController ac = (BaseFastController)ai.getController();
		
		/**
		 * 通过shiro进行用户权限的验证
		 */
		Subject currentUser = SecurityUtils.getSubject();
		//未登陆
		if(!currentUser.isAuthenticated()){
			ai.getController().redirect("/admin/login");
			return;
		}
		
		//检查是否本地管理员
		//本地管理员拥有所有权限
		if(currentUser.hasRole("localadmin")){
			//本地管理员
			ai.invoke();
			return;
		}

		final String ak = ai.getActionKey();
		//是否有权限
		//通过actionkey名称进行权限的验证
		if(!currentUser.isPermitted(ak)){
			//如果没有权限，则跳转至登陆页面
			//提示没有权限
			ai.getController().renderError(403,"/admin/error.jsp");
			//ai.getController().redirect("/admin/index");
			return;
		}
		
		ai.invoke();
		
		final boolean flag = ac.invokeResult;
		final String failReason = ac.failReason;
		
		final Record user = ac.getCurrentUser();
		if(Fast.me().checkBehavior(ak)){
			//log the behavior
			Fast.AynTask(new Runnable(){
	
				@Override
				public void run() {
					Bo bo = new Bo();
					bo.set("action",Fast.me().getBehavior(ak).get("title")+""+(flag?" SUCCESS":" ERROR"));
					bo.set("ip",user.get("ip"));
					bo.set("result",flag?1:0);
					if(!flag){
						//fail
						bo.set("reason",failReason);
					}
					bo.set("user",user.get("id"));
					bo.create();
					Db.save("sys_log", bo);
					Object tempO = Fast.me().getBehavior(ak).get("webhook");
					if(StrKit.notNull(tempO)){
						Fast.AynWebHook(tempO.toString(),null);
					}
				}
				
			});
		}
		
	}
	
}
